﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web;

namespace blackhouse.mojoPortalExtend.Urls {
    public sealed class UrlSupportProvider {

        #region Fields

        private UrlSupport supportedObject;
        private SiteSettings siteSettings;
        private PageSettings pageSettings;

        private string friendlyUrlText;
        private FriendlyUrl friendlyUrl;

        #endregion

        #region Constructors

        public UrlSupportProvider(UrlSupport obj) {
            this.supportedObject = obj;

            int siteId = 0;
            if (Int32.TryParse(HttpContext.Current.Request["SiteID"], out siteId))
                this.siteSettings = CacheHelper.GetSiteSettings(siteId);


            if (this.siteSettings == null && obj.DirectSiteId > 0)
                this.siteSettings = CacheHelper.GetSiteSettings(obj.DirectSiteId);

                if (this.siteSettings == null)
                this.siteSettings = CacheHelper.GetCurrentSiteSettings();

            int pageId = 0;
            if (HttpContext.Current != null && Int32.TryParse(HttpContext.Current.Request["pageid"], out pageId)) {
                this.pageSettings = CacheHelper.GetPage(pageId);
            }

            if (pageSettings == null)
                this.pageSettings = CacheHelper.GetCurrentPage();

            if (pageSettings.SiteId != siteSettings.SiteId)
                pageSettings = null;

            if (pageSettings == null)
                this.pageSettings = new PageSettings(siteSettings.SiteId, -1); // z -1 wybierze root page dla sita

            if (this.pageSettings.SiteId != this.siteSettings.SiteId)
                this.siteSettings = CacheHelper.GetSiteSettings(this.pageSettings.SiteId);
        }

        #endregion

        #region Methods

        public void Save() {
            if (this.supportedObject.OldUrl.Equals(this.supportedObject.NewUrl, StringComparison.CurrentCultureIgnoreCase)) return;

            this.friendlyUrlText = this.supportedObject.NewUrl.ReplaceEx("~/", String.Empty).RemovePolishChars().CleanStringForUrl();
            this.friendlyUrl = new FriendlyUrl(this.siteSettings.SiteId, this.friendlyUrlText);
            if (friendlyUrl.FoundFriendlyUrl && friendlyUrl.ItemGuid != this.supportedObject.Guid) { // znaleziono Url, ale nie należy on do tego obiektu
                this.supportedObject.ChangeToOtherNewUrl();
                this.Save();
                return;
            }

            if (!friendlyUrl.FoundFriendlyUrl && WebPageInfo.IsPhysicalWebPage("~/" + friendlyUrlText)) {
                this.supportedObject.ChangeToOtherNewUrl();
                this.Save();
                return;
            }
            if (!friendlyUrl.FoundFriendlyUrl) {
                this.friendlyUrl = this.CreateNewFriendlyUrl();
                this.friendlyUrl.Save();
            }
            if (this.supportedObject.OldUrl.Length > 0) { // URL został zmieniony, więc trzeba dodać przekierowanie
                this.AddRedirect();
                this.RemoveOldFriendlyUrl();
            }
            this.supportedObject.FriendlyUrl = this.friendlyUrl;
            this.supportedObject.Save();
        }

        private FriendlyUrl CreateNewFriendlyUrl() {
            FriendlyUrl newFriendlyUrl = new FriendlyUrl();
            newFriendlyUrl.SiteId = siteSettings.SiteId;
            newFriendlyUrl.SiteGuid = siteSettings.SiteGuid;
            newFriendlyUrl.PageGuid = this.pageSettings.PageGuid;
            newFriendlyUrl.Url = this.friendlyUrlText;
            newFriendlyUrl.RealUrl = this.GetFullRealUrl();
            return newFriendlyUrl;
        }

        private string GetFullRealUrl() {
            string url = this.supportedObject.RealUrl;
            char conn = '?';
            if (url.Contains(conn))
                conn = '&';
            if (url.IndexOf("pageId", 0, StringComparison.InvariantCultureIgnoreCase) == -1)
                url = url + conn + "pageId=" + pageSettings.PageId;
            return url;
        }

        private void AddRedirect() {
            string oldUrl = this.supportedObject.OldUrl.ReplaceEx("~/", String.Empty);
            string newUrl = this.supportedObject.NewUrl.ReplaceEx("~/", String.Empty);

            if (!RedirectInfo.Exists(siteSettings.SiteId, oldUrl) && !RedirectInfo.Exists(siteSettings.SiteId, newUrl)) {
                RedirectInfo redirect = new RedirectInfo();
                redirect.SiteGuid = siteSettings.SiteGuid;
                redirect.SiteId = siteSettings.SiteId;
                redirect.OldUrl = oldUrl;
                redirect.NewUrl = newUrl;
                redirect.Save();
            }
        }

        private void RemoveOldFriendlyUrl() {
            string oldUrl = this.supportedObject.OldUrl.ReplaceEx("~/", String.Empty);
            FriendlyUrl oldFriendlyUrl = new FriendlyUrl(siteSettings.SiteId, oldUrl);
            if ((oldFriendlyUrl.FoundFriendlyUrl) && (oldFriendlyUrl.ItemGuid == this.supportedObject.Guid)) {
                FriendlyUrl.DeleteUrl(oldFriendlyUrl.UrlId);
            }
        }

        public void OverridePage(PageSettings pageSettings) {
            this.pageSettings = pageSettings;
            if (!this.pageSettings.SiteGuid.Equals(this.siteSettings.SiteGuid))
                this.siteSettings = new SiteSettings(this.pageSettings.SiteGuid);
        }

        #endregion

    }
}
